package entity.model.members;

import entity.model.Entity;
import entity.model.EntityModel;
import entity.model.annotations.Hidden;
import entity.model.relationships.RelationshipFactory;
import misc.Title;

import java.lang.reflect.Field;

public class Attribute extends Entity.Member {

    private boolean fillable = false;
    private boolean hidden = false;
    private Object value;

    public Attribute(Entity entity, Title title) {
        super(entity, title);
    }

    public Attribute(Entity entity, Field field) {
        this(entity, Title.fromLowerCamel(getFieldName(field)));

        Class<?> type = field.getType();

        if (type.isPrimitive() || !type.getPackage().getName().contains("bamp")) {
            fillable = true;
            entity.decAttribute();
        }
        else if (EntityModel.INSTANCE.ENTITY_MAP.containsKey(type)) {
            RelationshipFactory.create(entity, field);

            entity.decAttribute();
        }
        else {
            EntityModel.INSTANCE.on(type, () -> {
                entity.decAttribute();
                RelationshipFactory.create(entity, field);
            });
        }

        hidden = field.isAnnotationPresent(Hidden.class);
    }

    private static String getFieldName(Field field) {
        String name = field.getName();
        return name.charAt(0) == '_' ? name.substring(1) : name;
    }

    public boolean isFillable() {
        return fillable;
    }

    public boolean isHidden() {
        return hidden;
    }

    public void value(Object value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return getTitle().toLowerCamel();
    }
}
